package com.wetao.lib_common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;

import com.wetao.lib_common.AppConfig;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.net.cookies.PersistentCookieStore;
import com.wetao.lib_common.view.graffiti.GraffitiView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

    /**
     * check if sdcard exist
     *
     * @return
     */
    public static boolean isSdcardExist() {
        return true;
        //return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * app缓存地址目录
     * @return
     */
    public static File getAppCacheFolder() {
        File appFolder = new File(AppConfig.PATH_DATA);
        return createOnNotFound(appFolder);
    }


    /**
     * 阅读推送pdf目录
     * @return
     */
    public static File getPDFFolder() {
        File appFolder = getAppCacheFolder();
        if (appFolder != null) {
            File downloadFolder = new File(appFolder, AppConfig.PATH_PDF);
            return createOnNotFound(downloadFolder);
        } else {
            return null;
        }
    }

    public static String getPicFilePath(Context mContext, String dir, String fileName, String strNext) {
        String userId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        //String dirPath = mContext.getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        dirPath = dirPath + File.separator + userId + File.separator + dir;
        File picDirF = new File(dirPath);
        if (!picDirF.exists()) {
            boolean mkdirs = picDirF.mkdirs();
            if (!mkdirs) {
                LogUtils.e("m1:创建失败picDir：" + dirPath);
            } else {
                LogUtils.i("m1:创建成功picDir");
            }
        }
        String filePath = dirPath + File.separator + fileName + strNext + ".png";
        LogUtils.i("m1: 图片存储的路径：" + filePath);
        return filePath;
    }

    public static String getPicDirPath(Context mContext, String dir) {
        String userId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        //String dirPath = mContext.getExternalFilesDir(null).getAbsolutePath();
        String dirPath = Constants.FILE_PATH;
        dirPath = dirPath + File.separator + userId + File.separator + dir;
        File picDirF = new File(dirPath);
        if (!picDirF.exists()) {
            boolean mkdirs = picDirF.mkdirs();
            if (!mkdirs) {
                LogUtils.e("m1:创建失败picDir：" + dirPath);
            } else {
                LogUtils.i("m1:创建成功picDir");
            }
        }
        LogUtils.i("m1: 图片存储文件夹的路径：" + dirPath);
        return dirPath;
    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        //dir.delete();// 删除目录本身
    }

    public static File getFileByPath(final String filePath) {
        return isSpace(filePath) ? null : new File(filePath);
    }

    public static boolean deleteFile(final String srcFilePath) {
        return deleteFile(getFileByPath(srcFilePath));
    }

    public static boolean deleteFile(final File file) {
        return file != null && (!file.exists() || file.isFile() && file.delete());
    }

    /**
     * 保存方法
     */
    public static void saveBitmap(Bitmap bitmap, String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
            //return;
        }
        String type = "";
        if ("PNG".equals(filePath.substring(filePath.lastIndexOf(".") + 1).toUpperCase())) {
            type = ".png";
        } else {
            type = ".jpg";
        }

        try {
            FileOutputStream out = new FileOutputStream(f);
            boolean result = false;
            if (".png".equals(type)) {
                result = bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            } else {
                result = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }
            out.flush();
            out.close();
            if(!result) {
                LogUtils.e("保存图片失败，马上会删除这一张图片");
                f = new File(filePath);
                if (f.exists()) {
                    f.delete();
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static String getFileName(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastSep = filePath.lastIndexOf(File.separator);
        return lastSep == -1 ? filePath : filePath.substring(lastSep + 1);
    }

    public static String getFileNameNoExtension(final String filePath) {
        if (isSpace(filePath)) return filePath;
        int lastPoi = filePath.lastIndexOf('.');
        int lastSep = filePath.lastIndexOf(File.separator);
        if (lastSep == -1) {
            return (lastPoi == -1 ? filePath : filePath.substring(0, lastPoi));
        }
        if (lastPoi == -1 || lastSep > lastPoi) {
            return filePath.substring(lastSep + 1);
        }
        return filePath.substring(lastSep + 1, lastPoi);
    }


    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    /**
     * 创建目录
     *
     * @param folder
     * @return 创建成功则返回目录，失败则返回null
     */
    private static File createOnNotFound(File folder) {
        if (folder == null) {
            return null;
        }

        if (!folder.exists()) {
            folder.mkdirs();
        }

        if (folder.exists()) {
            return folder;
        } else {
            return null;
        }
    }




    /***
     * 绝对路径获取缓存文件
     *
     * @param url
     * @return
     */
    public static File getPdfCacheFile(String url) {
        File cacheFile = new File(FileUtils.getPDFFolder()
                ,getPdfFileName(url));
        LogUtils.d("缓存文件 = " + cacheFile.toString());
        return cacheFile;
    }

    /***
     * 根据链接获取文件名（带类型的），具有唯一性
     *
     * @param url
     * @return
     */
    public static String getPdfFileName(String url) {
        String fileName = MD5Utils.hashKey(url) + "." + getPdfFileType(url);
        return fileName;
    }

    /***
     * 获取文件类型
     *
     * @param paramString
     * @return
     */
    public static String getPdfFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            LogUtils.d("paramString---->null");
            return str;
        }
        LogUtils.d("paramString:" + paramString);
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            LogUtils.d("i <= -1");
            return str;
        }


        str = paramString.substring(i + 1);
        LogUtils.d("paramString.substring(i + 1)------>" + str);
        return str;
    }
}
